package com.cloud.schedule.common.dynamic;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
	private static Map<Object, Object> datasourceMap = new ConcurrentHashMap<>();

	@Override
	protected Object determineCurrentLookupKey() {
		return DynamicDataSourceHolder.get();
	}

	public DataSource createDatasource(String id, String url, String username, String password,
			String driverClassName) {
		DataSource dataSource = DataSourceBuilder.create().url(url).username(username).password(password)
				.driverClassName(driverClassName).build();
		if (dataSource != null) {
			DataSourceUtils.put(id, id);
			datasourceMap.put(id, dataSource);
			super.setTargetDataSources(datasourceMap);
			super.afterPropertiesSet();
			return dataSource;
		}
		return null;
	}

}
